package com.zw.leave.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zw.leave.mapper.LeaveApplyMapper;
import com.zw.leave.service.LeaveApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zw.object.leave.LeaveApply;
import com.zw.object.result.Result;
import com.zw.object.vo.SearchLeaveVo;
import lombok.val;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 请假审批表 服务实现类
 * </p>
 *
 * @author zw
 * @since 2023-03-10
 */
@Service
public class LeaveApplyServiceImpl extends ServiceImpl<LeaveApplyMapper, LeaveApply> implements LeaveApplyService {

    @Override
    public Result saveLeaver(LeaveApply leaveApply) {
        Integer save  = baseMapper.insert(leaveApply);
        return save == 1 ? Result.ok():Result.fail();
    }

    @Override
    public Result searchLeaveAndPage(SearchLeaveVo leaveVo, String userId) {
        List<LeaveApply> leaveApplies = baseMapper.selectList(new LambdaQueryWrapper<LeaveApply>().eq(LeaveApply::getId, userId));
        LambdaQueryWrapper<LeaveApply> wrapper = new LambdaQueryWrapper<>();
        Page<LeaveApply> page = new Page<>(leaveVo.getPageNum(),leaveVo.getPageSize());
        if("学生".equals(leaveApplies.get(0).getDormitory())){
            wrapper.eq(LeaveApply::getUsername,leaveVo.getUsername());
            Page<LeaveApply> applyPage = baseMapper.selectPage(page, wrapper);
            return Result.ok(applyPage);
        }
        wrapper.like(StrUtil.isNotBlank(leaveVo.getUsername()), LeaveApply::getUsername, leaveVo.getUsername());
        wrapper.eq(leaveVo.getDeptId() != null, LeaveApply::getDeptId, leaveVo.getDeptId());
        wrapper.eq(leaveVo.getLeaveType() != null, LeaveApply::getLeaveType, leaveVo.getLeaveType());
        wrapper.eq(leaveVo.getStart() != null, LeaveApply::getStatus, leaveVo.getStart());
        if (StrUtil.isNotBlank(leaveVo.getStart()) && StrUtil.isNotBlank(leaveVo.getEnd())){
            DateTime a = DateUtil.parse(leaveVo.getStart() + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
            DateTime b = DateUtil.parse(leaveVo.getEnd() + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
            wrapper.between(LeaveApply::getCreateTime, a, b);
        }
        wrapper.orderByDesc(LeaveApply::getCreateTime);
        Page<LeaveApply> applyPage = baseMapper.selectPage(page, wrapper);
        return Result.ok(applyPage);
    }

    @Override
    public Result updateLeaveInfoById(LeaveApply leaveApply) {
        int update = baseMapper.updateById(leaveApply);
        return update == 1 ? Result.ok():Result.fail();
    }
}
